<?php

namespace app\mobile\controller;

use app\BaseController;
use Qcloud\Cos\Client;

class UploadController extends BaseController
{


    /**1
     * 腾讯云文件上传 COS
     */
    public function fileUpload()
    {
        $file = request()->file('file');

        $extend = pathinfo($file);
        $type = pathinfo($file, PATHINFO_EXTENSION);


        $type = $file->extension();
        /*$type = explode('/',$_FILES['file']['type']);
        $type = end($type);*/

        $file = fopen($file, 'rb');

        $cosClient = self::getCosClient();

        $fileName = self::getFilename().'.'.$type;

        $path = self::cosUpload($cosClient,$file,$fileName);

        $return['url'] = $path;
        $return['name'] = 123;

        //return $this->json(['msg'=>'上传成功','data'=>$path,'state'=>100]);
        return $this->suc_json('上传成功',$return);

    }

    /**
     * @return \EasyWeChat\OpenPlatform\Application|Client
     */
    public static function getCosClient()
    {
        //腾讯云cos
        $secretId = env('cos.secret_id'); //"云 API 密钥 SecretId";
        $secretKey = env('cos.secret_key'); //"云 API 密钥 SecretKey";

        $region = "ap-shanghai"; //设置一个默认的存储桶地域
        return new Client(
            array(
                'region' => $region,
                'schema' => 'https', //协议头部，默认为http
                'credentials' => array(
                    'secretId' => $secretId,
                    'secretKey' => $secretKey)
            )
        );
    }

    /**文件存储路径及名称
     * @return string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function getFilename()
    {
        /*Cache::store('redis')->incr('uploadId',1);
        $uploadId = Cache::store('redis')->get('uploadId');
        $ttl = Cache::store('redis')->ttl('uploadId');
        if($ttl<=0){
            Cache::store('redis')->expire('uploadId',86400);
        }*/

        $uploadId = mt_rand(1000,9999);

        return 'tqImage/web/tqis/'.time().$uploadId;
    }

    public static function cosUpload(Client $cosClient,$file,$filename)
    {
        try {
            $bucket = "examplebucket1-1306183894";

            $result = $cosClient->Upload(
                $bucket,
                $filename,
                $file,
                array('CacheControl'=>'no-cache')
            );

            return 'https://'.$result['Location'];
        } catch (\Exception $e) {
            dd($e->getMessage());
            echo "$e\n";
        }
    }

}